package com.web.itemService.Controller;

import com.alibaba.nacos.common.utils.ThreadUtils;
import com.aliyuncs.exceptions.ClientException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.web.itemService.service.userService;
import com.web.itemService.utils.getCode;
import com.web.itemService.utils.sendFileUtils;
import com.web.itemService.utils.sendMessage;
import entity.Result;
import entity.User;
import entity.codeCheck;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/api")
public class MainController {

    @Autowired
    com.web.itemService.utils.jwtUtils jwtUtils;
    @Autowired
    sendMessage sendMessage;
    @Autowired
    getCode getCode;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    userService userService;
    @Autowired
    sendFileUtils sendFileUtils;

    //TODO 这是线程隔离的实验接口
    @GetMapping("/get/first")
    public String first() {
        ThreadUtils.sleep(500);
        log.info("已经经过了mainService");
        return "访问成功 first ";
    }

    /**
     * 注册接口
     */
    @PostMapping("/regin/user")
    public Result reginUser(@RequestBody User user) throws ExecutionException, InterruptedException {

        User isUser = userService.findUserByUsernameAndPhone(user.getUsername(), user.getPhone());
        log.info("查找数据库是否已经存在该用户,isUser:{}", isUser);
        if (isUser != null) {
            return new Result("已经注册该账户", 201, null);
        }
        //配置redis里的信息验证
        String username = user.getUsername();
        String phone = user.getPhone();
        String password = user.getPassword();
        int code = getCode.getCode();
        //codeCheck检查体
        codeCheck codeCheck = new codeCheck(phone, new Date(System.currentTimeMillis()), username, password);
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(username, codeCheck, 60L, TimeUnit.SECONDS);
        if (!aBoolean) {
            log.info("已经存入了同名的redis检查:{}", redisTemplate.opsForValue().get(username));
            return new Result("有同名用户正在注册,请换一个用户名", 202, null);
        }

        log.info("验证码是：{}", code);
        sendMessage.sendCodeMessage(code, user.getPhone());
        return new Result("已发送验证码", 200, codeCheck);

    }

    /**
     * 验证码验证接口
     */
    @PostMapping("/regin/code")
    public Result login(@RequestBody Map<String, Object> code) {
        String getCode = (String) code.get("code");

        // 从 Map 中取出 checkCodeEntity，并手动转换为 codeCheck 类型
        Map<String, Object> checkCodeMap = (Map<String, Object>) code.get("checkCodeEntity");
        ObjectMapper objectMapper = new ObjectMapper();
        codeCheck checkCodeEntity = objectMapper.convertValue(checkCodeMap, codeCheck.class);

        String username = checkCodeEntity.getUsername();
        //获取redis内的验证码体

        codeCheck redisCodeCheck = (codeCheck) redisTemplate.opsForValue().get(username);
        if (redisCodeCheck == null) {
            return new Result("验证码错误", 401, null);
        } else {
            if (redisCodeCheck.equals(checkCodeEntity)) {
                User user = new User();
                user.setUsername(username);
                user.setPassword(checkCodeEntity.getPassword());
                user.setPhone(checkCodeEntity.getPhoneNumber());
                userService.register(user);
                return new Result("验证通过，已经注册，请登录", 200, null);
            } else {
                return new Result("验证码错误", 402, null);
            }
        }
    }

    /**
     * 登录接口
     *
     * @param user
     * @return
     */
    @PostMapping("/login/user")
    public Result loginUser(@RequestBody Map<String, Object> user) {
        String username = (String) user.get("username");
        String password = (String) user.get("password");
        log.info("username:{}", username);
        log.info("password:{}", password);
        User login = userService.login(username, password);
        if (login != null) {
            Integer id = login.getId();
            Map<String, Object> map = new HashMap<>();
            map.put("username", username);
            map.put("id", id);

            String jwt = jwtUtils.getJwt(map);
            return new Result("登录成功", 200, jwt);
        } else {
            return new Result("登录失败,账号或密码错误", 201, null);
        }
    }

    @PostMapping("/send/file/image")
    public Result sendFile(@RequestParam("file") MultipartFile file) throws ClientException, IOException {
        String url = sendFileUtils.sendFile(file);
        return new Result("已经接受图片", 200, url);
    }

}
